
import { setToken, getToken, removeToken } from '@/utils/auth'
import { getUserInfo, login, UserDetailById } from '@/api/user'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(ctx, loginForm) {
      const res = await login(loginForm)
      ctx.commit('updateToken', res.data)
      return res
    },
    async getProfile(ctx) {
      const res1 = await getUserInfo()
      // console.log(res1)
      const res2 = await UserDetailById(res1.data.userId)
      // console.log(res2)
      ctx.commit('updateUserInfo', { ...res1.data, ...res2.data })
      return { ...res1.data, ...res2.data }
    },
    logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('removeUserInfo')
    }
  }
}
